import 'dart:async';
import 'package:flutter/material.dart';
import '../model/verification_model.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../../components/toast_utils.dart';
import '../../models/user_info_model.dart';
import '../../manger/user_manger.dart';
import '../../main.dart';
import '../../manger/qysdk_manger.dart';
class ZhuxiaoStepFourController extends StatefulWidget {
  final String zxType;
  final String reasonText;
  final VerificationModel vermodel;

  ZhuxiaoStepFourController({this.zxType = "phone", this.reasonText = "", required this.vermodel});

  @override
  _ZhuxiaoStepFourControllerState createState() => _ZhuxiaoStepFourControllerState();
}

class _ZhuxiaoStepFourControllerState extends State<ZhuxiaoStepFourController> {
  TextEditingController codeController = TextEditingController();
  bool isCodeValid = false;
  String captchaVeri = "";
  int countdown = 0;
  Timer? _timer;

  // This is a mock method for the network request, you can implement your own network request logic
  Future<void> sendSMS() async {
    // Implement your network request here
    var params = {};
    if (widget.zxType == "phone") {
      params = {
        'type': "5",
        'captchaVerification': "",
      };
    } else {
      params = {
        'email': widget.vermodel.value,
        'sendType': "5",
        'captchaVerification': '',
      };
    }
    ToastUtils.showLoadingToast(context);

    try {
      final response = await NetworkUtils.post(
        widget.zxType == "phone" ? RequestCmd.sendcodeC : RequestCmd.sendEmailCode,
        body: params,
      );
      ToastUtils.dismissLoadingToast();
      final model = PhoneCodeModel.fromJson(response);
      if (model.code == 200) {
          ToastUtils.showCenterToast(context, model.msg ?? '发送成功');
          setState(() {
            countdown = 60;
          });
          _timer = Timer.periodic(Duration(seconds: 1), (timer) {
            if (countdown > 0) {
              setState(() {
                countdown--;
              });
            } else {
              _timer?.cancel();
            }
          });
      } 
    } catch (e) {
      print('Error fetching user info: $e');
    }
  }

  // This is a mock method for the network request, you can implement your own network request logic
  Future<void> submit() async {
    var params = {};
    if (widget.zxType == "phone") {
      params = {
        'type': "5",
        'detail': widget.reasonText,
        'code': codeController.text,
      };
    } else {
      params = {
        'email': widget.vermodel.value,
        'type': "5",
        'detail': widget.reasonText,
        'code': codeController.text,
      };
    }
    ToastUtils.showLoadingToast(context);

    try {
      final response = await NetworkUtils.post(
        widget.zxType == "phone" ? RequestCmd.logOutPhone : RequestCmd.logOutEmail,
        body: params,
      );
      ToastUtils.dismissLoadingToast();
      final responseData = response as Map<String, dynamic>;
      if (responseData['code'] == 200) {
        // 注销成功处理
        ToastUtils.showCenterToast(context, responseData['msg']?? '注销成功');
        await Future.delayed(Duration(milliseconds: 1500));
        if (mounted) {
          UserInfos.shared.cleanUserInfos();
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => MainPage(),
            ),
          );
        }
      } else {
        ToastUtils.showCenterToast(context, responseData['msg'] ?? '注销失败,请联系客服');
      }
    } catch (e) {
      print('Error fetching user info: $e');
    }
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        title: Text(AppLocalizations.of(context)!.identityVerification,style: const TextStyle(fontSize: 17)),
        actions: [
          TextButton.icon(
            onPressed: () {
              QYSDK.showQYSession();
            },
            icon: Image.asset('assets/images/zhuxiao0.png'),
            label: Text(isChineseLocale() ? '客服' : 'Customer',style: const TextStyle(fontSize: 16)),
            style: TextButton.styleFrom(
              foregroundColor: Colors.black,
            ),
          ),
        ],
      ),
      body: Padding(
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 40),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              widget.zxType == "phone" ? AppLocalizations.of(context)!.verifyPhone : AppLocalizations.of(context)!.verifyEmail,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 10),
            Text(
              widget.zxType == "phone" ? AppLocalizations.of(context)!.verifyPhoneForSecurity : AppLocalizations.of(context)!.verifyEmailForSecurity,
              style: TextStyle(fontSize: 14),
            ),
            SizedBox(height: 10),
            Text(
              widget.zxType == "phone" 
                ? "${AppLocalizations.of(context)!.verificationCodeToPhone}${widget.vermodel.code} ${widget.vermodel.value}" 
                : "${AppLocalizations.of(context)!.verificationCodeToEmail}${widget.vermodel.value}",
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            SizedBox(height: 30),
            // Input Field for Code
            TextField(
              controller: codeController,
              decoration: InputDecoration(
                labelText: AppLocalizations.of(context)!.pleaseEnter + AppLocalizations.of(context)!.verificationCode,
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(25)),
                contentPadding: EdgeInsets.symmetric(horizontal: 15),
                suffix: GestureDetector(
                  onTap: sendSMS,
                  child: Text(
                    countdown > 0 ? (isChineseLocale() ? '${countdown}秒后重试' : 'Sent ${countdown}') : AppLocalizations.of(context)!.send + AppLocalizations.of(context)!.verificationCode,
                    style: TextStyle(color: countdown > 0 ? Colors.grey : Color(0xFF5D5FEE)),
                  ),
                ),
              ),
              keyboardType: TextInputType.number,
              onChanged: (text) {
                setState(() {
                  isCodeValid = text.length >= 4;
                });
              },
            ),
            SizedBox(height: 40),
            // Submit Button
            SizedBox(
              width: double.infinity,
              height: 50,
              child: ElevatedButton(
                onPressed: isCodeValid ? submit : null,
                child: Text(AppLocalizations.of(context)!.submit),
                style: ElevatedButton.styleFrom(
                  backgroundColor: isCodeValid ? Color(0xFF5D5FEE) : Color(0xFF5D5FEE).withValues(alpha: 0.7),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                  padding: EdgeInsets.symmetric(horizontal: 35),
                  foregroundColor: isCodeValid ? Colors.white : Colors.black,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
